﻿<?php

	require 'system/config.php';
	require 'system/database.php';
	
	if(isset($_REQUEST['action']) && isset($_REQUEST['id']) && !empty($_REQUEST['action']) && !empty($_REQUEST['id'])){
		
		$id 	= DBEscape( strip_tags( trim( $_REQUEST['id'] ) ) );
		
		switch($_REQUEST['action']){
			case 1:
				DBUpDate( 'posts', array('status' => 1), "id ='{$id}'" );
			break;
		}
		
		header('location: chat.php');
		
	}

	session_start();
	$_SESSION['update'] = '0';
	include_once "config.php";
	require_once "classe/BD.php";
	$bd = new BD();
	$bd->conexao();
?>

<?php
include_once 'restrito.php';

	if($_SESSION['valida'] != 0){
			
?>

<?php
		
	if($_SESSION['update'] == '1'){
		echo "<script> alert ('Dados alterados com sucesso');</script>";
		$_SESSION['update'] = 0;
	}else if($_SESSION['update'] == '2'){
		echo "<script> alert ('Dados fornecidos incorretos');</script>";
		$_SESSION['update'] = 0;
	}
?>
<!doctype html>
<html lang="pt-BR">
    <head>
        <meta charset="utf-8">
        <title> MIDEA </title>
        <link rel="icon" href="images/favicon-m.png">
        <link rel="stylesheet" type="text/css" media="all" href="css/styleChat.css">
       	<link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css">
       	<script src="//code.jquery.com/jquery-1.10.2.js"></script>
  		<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
        <script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>       
        <script type="text/javascript" src="js/functions.js"></script>
        <script type="text/javascript" src="js/chat.js"></script>
        <script type="text/javascript" src="js/js.js"></script>
        <script type="text/javascript" src="js/busca.js"></script>
        <script type="text/javascript" src="js/show-hide.js"></script>
        <script type="text/javascript" src="js/modal.js"></script>
        <script type="text/javascript">
        	$(document).ready(function() {
                $('input[name=q]').bind('input', function(){
					var s = $(this).val();
					var conta = $(this).val().length;
					
					if(conta >= 1){
						$.post('pesquisa.php', { s_post:s}, function(retorna){
							$('#resultado #exibe').html(retorna);	
						});
					}else {
						$('#resultado #exibe').html('Pesquise por alguém');	
					}
				});
				
				$('#pesquisa').submit(function(){
					
				})
            });
        </script>
        <script type="text/javascript">
        	$(document).ready(function() {
                $('#resultado').hide();
				$('#exibe').hide();

				$('#q').keyup(function() {
                    $('#resultado').show();
					$('#exibe').show();
                });
            });
        </script>
   </head>
  
    <body>
    	<!-- menu prncipal -->
    	<header>
        	<div id="config">
                <a class="menu pull-left" data-position="left" href="#" title="Menu" rel="modal">
                     <div class="bar"></div>
                     <div class="bar"></div>
                     <div class="bar"></div>
                </a>      
            </div> 
    		<!-- fim -->
               
            <!-- logo do site -->
            <div id="logo"><img src="images/White.png" width="220" height="40"></div>	
            <!-- fim -->
            
            <!-- barra de pesquisa -->
            <div id="formulario">
           
            	<form id="pesquisa" action="" method="post" enctype="multipart/form-data" autocomplete="off">
                    <input type="submit" class="sub" id="sub" name="sub" data-icon="search" value="">
                    <input type="search" class="search" id="q" name="q" placeholder="Pesquisar por alguém...">	
         		</form> 
			
            </div>
            <!-- fim -->
           
            <!-- resultados da pesquisa -->
            <div id="resultado">
                <div id="exibe">
                </div>
                <div style="clear:both;"></div>
            </div>
            
            <!--Mostrando o nome e a imagem do usuario logado do lado direito da página -->
            <div id="user">
                   <?php 
                        $seleciona_user = $bd->conexao()->prepare("SELECT nome FROM usuario WHERE id = ?");
                        $seleciona_user->execute(array($_SESSION['id_user']));
                        
                        if($seleciona_user->rowCount() == 0):
                            echo '<p style="color:#222">Nenhum usario encontrado</p>';
                        else:	
                            while($usuario = $seleciona_user->fetchObject()):
                                echo "<p style='margin-top:-30px;
									float:right;
									position:relative;
									font-family:Gotham, Helvetica Neue, Helvetica, Arial, sans-serif;
									font-weight:bold;
									font-size:18px;
									color:#FFF;'>".$usuario->nome."</p>&nbsp;"
								;
                            endwhile;
                        endif;
        
                    ?>
             </div>
            
            
            <!-- <div id="CS">
                <nav>
                    <ul>
                    	<li><a href="chat.php"> Inicial </a></li><br>
                        <li><a href="#" rel="modal"> Configurações </a></li><br>
                        <li> <a href="sair.php"> Sair </a></li>
                    </ul>
                </nav>    
            </div>--> 
            <!-- fim -->
    	</header>
        <!-- fim -->
        <div class="overlay"></div>
   
    	<div id="contatos">
        <span class="online" id="<?php echo $_SESSION['id_user']; ?>"></span>
        	<ul>
            	<?php 
					$seleciona_user = $bd->conexao()->prepare("SELECT * FROM usuario WHERE id != ? ORDER BY nome");
					$seleciona_user->execute(array($_SESSION['id_user']));
					if($seleciona_user->rowCount() == 0) :
						echo '<p style="color:#222">Desculpa, não há contatos ainda</p>';
					else :
						while($usuario = $seleciona_user->fetchObject()):	
				?>
                <li>
                	<span class="type" id="<?php echo $usuario->id; ?>"></span>
                	<a href="javascript:void(0);" nome="<?php echo $usuario->nome; ?>" id="<?php echo $usuario->id;?>" 			class="comecar">
						<?php
							echo "<img style='float:left;
								margin-left:-5px;
								margin-top:-6px;
								width:30px;
								height:30px;
								border-radius:100%;' src='fotos/".$usuario->nome_final."'>"
							;
							echo  "<p style='margin-top:3px;margin-left:35px;'>".$usuario->nome."</p>"; 
                        ?>
                    </a>
                </li>
                <?php endwhile; endif; ?>
     	
            </ul>
        </div>
        
        <div style="position:absolute; top:0; right:0;" id="retorno"></div>
        <div id="janelas"></div> 
        
        <div id="visualizar">
        
         
             <?php 
                        $seleciona_user = $bd->conexao()->prepare("SELECT nome_final FROM usuario WHERE id = ?");
                        $seleciona_user->execute(array($_SESSION['id_user']));
                        
                        if($seleciona_user->rowCount() == 0):
                            echo '<p style="color:#222">Nenhuma imagem cadastrada</p>';
                        else:	
                            while($usuario = $seleciona_user->fetchObject()):
                                echo "<img id='usuario' style='float:right;margin-right:5px;' src='fotos/".$usuario->nome_final."'>";
                            endwhile;
                        endif;
        
              ?>
        
        
           	  <nav>
                    <ul>
                    	<li>
                        	<a href="chat.php"> &nbsp;&nbsp;
                        		<img src="images/reload.png"
                                width="16"
                                height="16" 
                            	style="position:absolute;
                                margin-top:2px;"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Atualizar 
                            </a>
                        </li>
                    	<li>
                        	<a href="#"> &nbsp;&nbsp;
                        		<img src="images/comments.png" 
                            	style="position:absolute;
                                margin-top:2px;"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Mensagens 
                            </a>
                        </li>
                        <li>
                        	<a href="#" rel="modal"> &nbsp;&nbsp;
                            	<img src="images/cog.png" 
                                style="position:absolute;
                                margin-top:2px;"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Configurações
                            </a>    
                        </li>
                        <li>
                        	<a href="sair.php"> &nbsp;&nbsp;
                        		<img src="images/logout-icon.png" 
                                width="18" 
                                height="18" 
                            	style="position:absolute;
                                margin-left:-3px;
                                margin-top:2px;"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Sair
                            </a>
                        </li>
                    </ul>
              </nav> 
        </div>
        
        <div id="ocultar" title="Voltar"><h1>&larr;</h1></div>
         
      
    	<script type="text/javascript" src="js/main.js"></script>
        
        
        <!--	
        <div class="window" id="janela1">
        <a href="#" class="fechar">X</a>
        	<div id="page">
                <div class="box">
                    <div class="title">Nome</div>
                    <div class="container show">
                          <form method="post" id="formulario" action="update/nome.php">
                            <input type="text" name="nome" placeholder="Digite o novo nome" class="camp" required><br>
                            <input type="password" name="senha" placeholder="Digite a senha atual" class="camp" required><br>
                            <input type="submit" value="Enviar" class="bot">
                          </form>
                    </div>    
                </div>
    
                <div class="box">
                    <div class="title">Senha</div>
                    <div class="container hide">
                      <form method="post" action="update/senha.php">
                         <input type="password" placeholder="Digite a senha atual" class="camp" name="senha" required><br>
                         <input type="password" placeholder="Digite a nova senha" class="camp" name="senhan" required><br> 
                         <input type="password" placeholder="Digite a nova senha novamente" class="camp" name="senhanc" required><br>
                        <input type="submit" value="Enviar" class="bot">
               
                    </form> 
                    </div>  
                </div>
    
                <div class="box">
                    <div class="title">E-mail</div>
                    <div class="container hide">
                          <form method="post" action="update/email.php">
                            <input type="email" placeholder="Digite o novo email" class="camp" required name="email"><br>
                            <input type="password" placeholder="Digite sua senha atual" class="camp" required name="senha"><br>
                            <input type="submit" value="Enviar" class="bot">
                          </form>
                    </div>    
                </div>

        	</div>
         </div>	
            -->
	 
        <!--mascara para cobrir o site -->  
        <div id="mascara"></div>
        
        <?php
            if(isset($_REQUEST['publicar'])){
                $form['autor']     = $_SESSION['valida'];
                $form['data']      = date('Y-m-d H:i:s', strtotime('-240 min'));
                $form['conteudo']  = str_replace( '\r\n', "<br>" , DBEscape(trim($_REQUEST['conteudo'])));
                
                $form = DBEscape($form);
                
                if(empty($form['conteudo'])){
                }else{
                                            
                    if(DBCreate('posts', $form)){
                    	echo "<script> alert ('Sua postagen foi envida com sucesso!');</script>";
						header('location: chat.php');
                    }else{
                        echo "<script> alert ('Desculpe, ocorreu um erro...');</script>";
					}
                }
			}
        ?> 
        
        <form id="publico" method="post" action="" enctype="multipart/form-data">
            <textarea id="postar" name="conteudo" placeholder="Publique aqui seus textos, comentários e opiniões." wrap="hard" required></textarea>
            <input type="submit" class="publicar" name="publicar" value="Publicar">    
        </form>
        
        <div id="post">
        	<?php
             
                $posts = DBRead( 'posts', "WHERE status = 0 ORDER BY data DESC" ); 
                
                if(!$posts)
                    echo '<center><h2>Desculpe, nenhuma postagem encontrada!</h2></center>';
                else
                    foreach( $posts as $post ):
					
						$seleciona_user = $bd->conexao()->prepare("SELECT nome,nome_final FROM usuario WHERE id = '".$post['autor']."'");
						$seleciona_user->execute(array($_SESSION['id_user']));
						$usuario = $seleciona_user->fetchObject();
					
					
				if($_SESSION['valida'] == $post['autor'])
					$ver = true;
				else
					$ver = false;
					$post['autor'] = $usuario->nome;
        	 ?>
         	<div class="postagem">
                    <?php 
						echo "<img src='fotos/".$usuario->nome_final."' 
								width='45px' 
								height='45px' 
								style='margin-left:5px;
								margin-top:5px;'>"
						; 
						
						echo "<p style='
								margin-left:65px;
								margin-top:-40px;
								font: 16px Gotham, Helvetica Neue, Helvetica, Arial, sans-serif;
								font-weight:bold;
								color:#004080'>".$post['autor'].
							"</p>"
						;
					?>
                    <?php 
						echo "<p style='
								margin-left:245px;
								margin-top:-20px;
								color:#06F;'>".date('d/m/Y H:i:s' , strtotime($post['data'])).
							 "</p>"
						; 
					?> 
					<?php if( $ver ){ ?>
                     <p style="margin-left:420px;margin-top:-20px;">|&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                     	<a style="
                        	 text-decoration:none;
                             color:#06F;" 
                             href='?action=1&&id=<?php echo $post['id']; ?>' 
                             title='Deletar'> 
                    		 <img src="images/6239_32x32.png" 
                            	 width="16" 
                            	 height="16" 
                            	 style="position:absolute;
                             	 margin-left:-20px;"> Deletar
                         </a>
                      </p>
                    <?php } ?>
                </p>
            	
                <hr style="margin-top:30px;">
                		
                <p style="margin-top:10px;margin-left:20px;">
                	
                    <?php echo nl2br( $post['conteudo'] ); ?>
                </p>
            </div>    
        	<?php endforeach; ?>
         
        </div> 
        
        <footer>
        
        </footer>
    </body>
</html>

<?php
}else{
		header('location:index.php');
}
?>